package com.matea.order.message;

import com.fasterxml.jackson.core.type.TypeReference;
import com.matea.order.utils.JsonUtil;
import com.matea.product.common.ProductInfoOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.transaction.Transactional;
import java.util.List;

/**
 * Created by Matea on 2019/2/10.
 */
@Component
@Slf4j
@Transactional
public class ProductInfoReceiver {

    private  static  final  String PRODUCT_STOK_TEMPLATE ="product_stock_%s";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(queuesToDeclare = @Queue("productInfo"))
    public  void process(String message){
        //message => ProductInfoOutput
        List<ProductInfoOutput> productInfoOutputList =( List<ProductInfoOutput>)JsonUtil.fromJson(message, new TypeReference<List<ProductInfoOutput>>() { });
        log.info("*****************从队列【{}】接收到消息：{}","productInfo",productInfoOutputList);

        //存储到redis中
        for (ProductInfoOutput productInfoOutput : productInfoOutputList){
            stringRedisTemplate.opsForValue().set(String.format(PRODUCT_STOK_TEMPLATE,productInfoOutput.getProductId()),
                    String.valueOf(productInfoOutput.getProductStock()));
        }

    }

}
